<template>
  <view class="index">
    <view class="header">
      <text class="header-title">胎儿体重计算器</text>
    </view>
    <view class="center">
      <view class="ind_from">
        <view class="row">
          <view class="label">双顶径BPD</view>
          <view class="value">
            <input
              class="input"
              v-model.number="formData.bpd"
              type="digit"
              placeholder="请输入BPD"
              maxlength="5"
            />
            <text class="unit">cm</text>
            <text class="input-tip">{{ inputTips.bpd }}</text>
          </view>
        </view>
        <view class="row">
          <view class="label">腹围AC</view>
          <view class="value">
            <input
              class="input"
              v-model.number="formData.ac"
              type="digit"
              placeholder="请输入AC"
              maxlength="5"
            />
            <text class="unit">cm</text>
            <text class="input-tip">{{ inputTips.ac }}</text>
          </view>
        </view>
        <view class="row">
          <view class="label">股骨长FL</view>
          <view class="value">
            <input
              class="input"
              v-model.number="formData.fl"
              type="digit"
              placeholder="请输入FL"
              maxlength="5"
            />
            <text class="unit">cm</text>
            <text class="input-tip">{{ inputTips.fl }}</text>
          </view>
        </view>
      </view>
      <view class="btn-group">
        <view class="btn primary" @click="submit">{{ isUnlock ? "计算" : "看广告获取计算结果" }}</view>
        <view class="btn secondary" @click="resetForm">重置</view>
      </view>
      <view class="formula-tip" @click="showFormula = !showFormula">
        计算公式说明
        <text class="arrow" :class="{ 'arrow-up': showFormula }">▼</text>
      </view>
      <view v-if="showFormula" class="formula-content">
        体重(克) = 10^(1.3596 + 0.0064*BPD + 0.0424*AC + 0.174*FL + 0.00061*BPD*AC - 0.00386*AC*FL)
      </view>
      <view class="result" :class="{ 'result-empty': !showResult }">
        <view class="result-icon">
          <view class="icon-success"></view>
        </view>
        <view class="result-content">
          <view class="result-title">胎儿体重约为</view>
          <template v-if="showResult">
            <view class="result-value">
              <text class="value-number">{{ result.efw.toFixed(2) }}</text>
              <text class="value-unit">克</text>
            </view>
            <view class="result-value kg">
              <text class="value-number">{{ (result.efw / 1000).toFixed(2) }}</text>
              <text class="value-unit">千克</text>
            </view>
          </template>
          <view class="suggestion">{{ weightSuggestion }}</view>
        </view>
      </view>
      <button class="addShortcut" open-type="addShortcut" :bindaddshortcut="eventHandler">添加到桌面</button>
      <button class="share" open-type="share">分享</button>
      <view class="pub_ad_banner">
        <!-- #ifdef MP-TOUTIAO -->
        <ad
          :unit-id="adBannerIdDouyin"
          :ad-intervals="30"
          :fixed="false"
          type="banner"
          scale="100"
        />
        <!-- #endif -->
        <!-- #ifdef MP-KUAISHOU -->
        <ad :type="100011054" :unit-id="adBannerIdKuaishou"></ad>
        <!-- #endif -->
      </view>
    </view>
  </view>
</template>

<script>
import {
  showAdConfirmModal,
  adVideoShow,
  adBannerIdDouyin,
  adBannerIdKuaishou,
} from "@/common/ad";
export default {
  data() {
    return {
      adBannerIdDouyin: adBannerIdDouyin,
      adBannerIdKuaishou: adBannerIdKuaishou,
      showResult: false,
      isUnlock: false,
      showFormula: true,
      formData: {
        bpd: "",
        ac: "",
        fl: "",
      },
      result: {
        efw: 0,
      },
      weightSuggestion: "请输入BPD、AC、FL数值进行计算",
      inputTips: {
        bpd: "正常范围：2.0-10.0cm",
        ac: "正常范围：10.0-40.0cm",
        fl: "正常范围：1.0-8.0cm"
      },
      inputRanges: {
        bpd: { min: 2.0, max: 10.0, unit: 'cm' },
        ac: { min: 10.0, max: 40.0, unit: 'cm' },
        fl: { min: 1.0, max: 8.0, unit: 'cm' }
      }
    };
  },
  onLoad() {
    // 初始化时显示公式
    this.showFormula = true;
  },
  methods: {
    eventHandler(e) {
      if (e.detail.errNo) {
        this.global.toast("添加到桌面失败");
      } else {
        this.global.toast("添加到桌面成功");
      }
    },
    validateInput(field, value) {
      if (!value && value !== 0) {
        return {
          valid: false,
          message: `请输入${this.getFieldLabel(field)}`
        };
      }

      const num = parseFloat(value);
      if (isNaN(num)) {
        return {
          valid: false,
          message: `${this.getFieldLabel(field)}必须是数字`
        };
      }

      const range = this.inputRanges[field];
      if (num < range.min || num > range.max) {
        return {
          valid: false,
          message: `${this.getFieldLabel(field)}超出正常范围(${range.min}-${range.max}${range.unit})`
        };
      }

      return { valid: true };
    },

    getFieldLabel(field) {
      const labels = {
        bpd: '双顶径BPD',
        ac: '腹围AC',
        fl: '股骨长FL'
      };
      return labels[field];
    },

    validateAllInputs() {
      const fields = ['bpd', 'ac', 'fl'];
      for (const field of fields) {
        const validation = this.validateInput(field, this.formData[field]);
        if (!validation.valid) {
          this.weightSuggestion = validation.message;
          return false;
        }
      }
      return true;
    },

    calculate() {
      if (!this.validateAllInputs()) {
        this.showResult = false;
        return;
      }

      const bpd = parseFloat(this.formData.bpd);
      const ac = parseFloat(this.formData.ac);
      const fl = parseFloat(this.formData.fl);

      const logEFW =
        1.3596 +
        0.0064 * bpd +
        0.0424 * ac +
        0.174 * fl +
        0.00061 * bpd * ac -
        0.00386 * ac * fl;
      
      this.result.efw = Math.pow(10, logEFW);
      
      // 根据孕周给出更详细的建议
      const week = this.calculateWeek(bpd);
      if (this.result.efw < 2500) {
        this.weightSuggestion = `当前孕周约${week}周，胎儿体重偏低，建议：\n1. 增加营养摄入\n2. 适当补充蛋白质\n3. 咨询医生进行专业指导`;
      } else if (this.result.efw > 4000) {
        this.weightSuggestion = `当前孕周约${week}周，胎儿体重偏高，建议：\n1. 控制饮食热量\n2. 适当运动\n3. 定期产检监测`;
      } else {
        this.weightSuggestion = `当前孕周约${week}周，胎儿体重正常，建议：\n1. 保持均衡饮食\n2. 规律作息\n3. 定期产检`;
      }
      this.showResult = true;
    },
    calculateWeek(bpd) {
      // 根据BPD估算孕周
      const week = Math.round(bpd * 4 + 5);
      return week;
    },
    getResult() {
      this.calculate();
      this.isUnlock = true;
    },
    submit() {
      if (this.formData.bpd == "") {
        this.global.toast("请输入双顶径BPD");
        return;
      }
      if (this.formData.ac == "") {
        this.global.toast("请输入腹围AC");
        return;
      }
      if (this.formData.fl == "") {
        this.global.toast("请输入股骨长FL");
        return;
      }
      if (!this.isUnlock) {
        showAdConfirmModal(() => {
          try {
            adVideoShow(() => {
              this.getResult();
            });
          } catch (error) {
            this.getResult();
          }
        });
      } else {
        this.getResult();
      }
    },
    resetForm() {
      this.formData = { bpd: "", ac: "", fl: "" };
      this.showResult = false;
      this.weightSuggestion = "请输入BPD、AC、FL数值进行计算";
      this.isUnlock = false;
    },
  },
};
</script>

<style scoped lang="scss">
.index {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20rpx;
}

.header {
  padding: 40rpx 0;
  text-align: center;
  .header-title {
    font-size: 44rpx;
    font-weight: 600;
    color: #2c3e50;
    letter-spacing: 2rpx;
  }
}

.center {
  max-width: 800rpx;
  margin: 0 auto;
}

.ind_from {
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  .row {
    padding: 24rpx 30rpx;
    display: flex;
    align-items: center;
    border-bottom: 2rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      width: 180rpx;
      font-size: 32rpx;
      color: #2c3e50;
      font-weight: 500;
    }
    
    .value {
      flex: 1;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      
      .input {
        flex: 1;
        height: 80rpx;
        padding: 0 20rpx;
        font-size: 32rpx;
        background: #f8f9fa;
        border-radius: 8rpx;
        border: 2rpx solid #e9ecef;
        transition: all 0.3s ease;
        
        &:focus {
          border-color: #007aff;
          background: #ffffff;
        }

        &.error {
          border-color: #dc3545;
          background: #fff5f5;
        }
      }
      
      .unit {
        margin-left: 16rpx;
        color: #6c757d;
        font-size: 28rpx;
      }

      .input-tip {
        width: 100%;
        margin-top: 8rpx;
        font-size: 24rpx;
        color: #6c757d;
      }
    }
  }
}

.btn-group {
  display: flex;
  gap: 20rpx;
  margin: 40rpx 0;
  
  .btn {
    flex: 1;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 500;
    border-radius: 12rpx;
    transition: all 0.3s ease;
    
    &.primary {
      background: #007aff;
      color: #ffffff;
      box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
      
      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 6rpx rgba(0, 122, 255, 0.2);
      }
    }
    
    &.secondary {
      background: #f8f9fa;
      color: #6c757d;
      border: 2rpx solid #e9ecef;
      
      &:active {
        background: #e9ecef;
      }
    }
  }
}

.formula-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  margin: 30rpx 0;
  color: #007aff;
  font-size: 28rpx;
  
  .arrow {
    transition: transform 0.3s ease;
    
    &.arrow-up {
      transform: rotate(180deg);
    }
  }
}

.formula-content {
  background: #f8f9fa;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #495057;
  text-align: center;
  margin-bottom: 30rpx;
}

.result {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  margin: 30rpx 0;
  
  .result-icon {
    text-align: center;
    margin-bottom: 20rpx;
    
    .icon-success {
      width: 80rpx;
      height: 80rpx;
      background: #e3fcef;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      
      &::after {
        content: "✓";
        color: #00b894;
        font-size: 40rpx;
      }
    }
  }
  
  .result-content {
    text-align: center;
    
    .result-title {
      font-size: 32rpx;
      color: #2c3e50;
      margin-bottom: 20rpx;
    }
    
    .result-value {
      margin: 16rpx 0;
      
      &.kg {
        margin-top: 8rpx;
      }
      
      .value-number {
        font-size: 48rpx;
        font-weight: 600;
        color: #007aff;
      }
      
      .value-unit {
        font-size: 28rpx;
        color: #6c757d;
        margin-left: 8rpx;
      }
    }
    
    .suggestion {
      margin-top: 24rpx;
      padding: 16rpx;
      background: #fff3e0;
      border-radius: 8rpx;
      color: #f57c00;
      font-size: 28rpx;
      white-space: pre-line;
      line-height: 1.6;
    }
  }

  &.result-empty {
    .result-icon {
      .icon-success {
        background: #f8f9fa;
        &::after {
          content: "?";
          color: #6c757d;
        }
      }
    }
    
    .result-content {
      .result-value {
        display: none;
      }
    }
  }
}

.pub_ad_banner {
  margin: 40rpx 0;
}
</style>